import { IHttpResponse, IParam } from '@/core/interface';
import { HttpResponse } from '@/core/utils';
import { ControlVOBase } from '../control-vo';
import { CtrlServiceBase } from './ctrl-service-base';

/**
 * 面板部件服务
 *
 * @class PanelService
 */
class PanelService<T extends ControlVOBase> extends CtrlServiceBase<T> {
	handleResponse(response: IHttpResponse, opts: any = {}) {
		if (!response.data) {
			return response;
		}
		let result = null;
		const handleResult = (isCreate: boolean = false) => {
			if (response.data instanceof Array) {
				result = [];
				response.data.forEach((item: any, index: number) => {
					result.push(this.newControlVO(item));
				});
			} else {
				result = this.newControlVO(response.data);
			}
			// response状态，头文件
			if (response.config) {
				if (response.config['x-page']) {
					Object.assign(response, { page: Number(response.config['x-page']) });
				}
				if (response.config['x-per-page']) {
					Object.assign(response, {
						size: Number(response.config['x-per-page']),
					});
				}
				if (response.config['x-total']) {
					Object.assign(response, {
						total: Number(response.config['x-total']),
					});
				}
			}
			response.data = result;
		};
		handleResult();
		return response;
	}

	async search(
		action: string,
		context: IParam = {},
		data: IParam = {}
	): Promise<IHttpResponse> {
		const { data: Data, context: Context } = this.handleRequestData(
			context,
			data
		);
		try {
			await this.beforeAsyncAction();
			const response = await this.appEntityService[
				action ? action : 'FetchDefault'
			](Context, Data);
			this.handleResponse(response);
			return response;
		} catch (error) {
			return new HttpResponse(error, null, 500);
		}
	}
}
export default PanelService;
